<?php
class CategoryController extends Zend_Controller_Action {

    protected $_category;
    protected $_mapper;

    public function init()
    {
        $id = (int) $this->_getParam('id',null);
        $mapper = new Model_Category_Mapper();
        $this->_category = $mapper->load($id);
        $this->_mapper = $mapper;
    }

    public function indexAction()
    {
        $categorys = $this->view->categorys = $this->_category->childrens;
    }

    public function productsAction()
    {
        
        if(!$this->_category){
            $this->_forward('index');
        }
        $categorys = $this->view->categorys = $this->_category->childrens;
        $parents = $this->view->parents = $this->_category->parents;
        $size = (int) $this->_getParam('size');
        $price = (int) $this->_getParam('price');
        $brand = $this->_getParam('brand');
        $class = $this->_getParam('class');
        $paginator = $this->_category->getProductsByPage((int) $this->_getParam('page',0), 30,
            array('size'=>$size, 'brand'=>$brand, 'category'=>$class), array('price'=>$price));
        $paginator->setView($this->view);
        $this->view->assign(array(
            'size'=>$size,
            'price'=>$price, 
            'brand'=>$brand, 
            'products'=>$paginator,
            'class'  => $class,
            'category' => $this->_category
        ));
        $this->view->headTitle()->append($this->_category->name);
    }

    public function editAction()
    {
        
        $form = new Form_Category($this->_category, $this->_mapper);
        $this->view->form = $form;
        if($this->getRequest()->isPost()){
            if($form->isValid($this->getRequest()->getPost()))
            {
                $this->_category = $this->_mapper->fill($this->_category,$this->getRequest()->getPost());
                $this->_mapper->save($this->_category);
                $this->_redirect('/category/products/id/'.$this->_category->parent_id);
            }
        }
        $this->view->headTitle()->append("Редактирование категории '{$this->_category->name}'");
    }

    public function deleteAction()
    {
        $this->_mapper->delete($this->_category);
        $this->_redirect('/category/products/id/'.$this->_category->parent_id);
    }
    
    public function parseAction()
    {
        Zend_Layout::getMvcInstance()->disableLayout();
        $XML = new Model_Category_XML();
        $XML->parse();
    }
}

